package com.lagou.edu.utils;

import com.lagou.edu.annotation.Service;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Optional;

/**
 * @author zyy
 * @date 2020/11/22 12:56 下午
 * @description
 */
@Service
public class ConnectionUtils {
    //存储当前线程的连接
    private ThreadLocal<Connection> threadLocal = new ThreadLocal();

    public Connection getCurrentThreadConn(){
        Connection connection = threadLocal.get();
        connection = Optional.ofNullable(connection).orElseGet(() -> {
            try {
                return createCurrent();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            return null;
        });
        return connection;
    }

    private Connection createCurrent() throws SQLException {
        Connection connection = DruidUtils.getInstance().getConnection();
        threadLocal.set(connection);
        return connection;
    }
}
